<template>
  <div class="main-content">
    <div class="screen-frame clearfix">
      <div class="col-md-6 col-lg-5">
        <div class="form-horizontal">
          <div class="form-group">
            <label for=""
                   class="col-md-3 col-sm-2 control-label">楼盘：</label>
            <div class="col-md-8 col-sm-10">
              <el-select class=""
                         v-model="params.premisesId"
                         filterable
                         placeholder="请选择"
                         :clearable="true"
                         style="width:100%">
                <el-option v-for="item in premisesList"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id">
                </el-option>
              </el-select>
            </div>
          </div>
        </div>
        <div class="form-horizontal">
          <div class="form-group">
            <label for=""
                   class="col-md-3 col-sm-2 control-label">分销佣金方式：</label>
            <div class="col-md-8 col-sm-10">
              <select class="form-control"
                      v-model="params.commissionMode">
                <option value="">全部</option>
                <option v-for="(value,key) in commissionModeList"
                        :value="key">{{value}}</option>
              </select>
            </div>
          </div>
        </div>
        <div class="form-horizontal">
          <div class="form-group">
            <label for=""
                   class="col-md-3 col-sm-2 control-label">创建时间：</label>
            <div class="col-md-8 col-sm-10">
              <input type="date"
                     class="form-control"
                     style="width:45%;float:left"
                     v-model="params.createTime" />
            </div>
          </div>
        </div>
      </div>
      <div class="col-md-6 col-lg-5">

        <div class="form-horizontal">
          <div class="form-group">
            <label for=""
                   class="col-md-3 col-sm-2 control-label">合作机构：</label>
            <div class="col-md-8 col-sm-10">
              <select class="form-control"
                      v-model="params.agentOrgId">
                <option value="">全部</option>
                <option v-for="c in companyList"
                        :value="c.agentCompany">{{c.agentCompanyName}}</option>
              </select>
            </div>
          </div>
        </div>
        <div class="form-horizontal">
          <div class="form-group">
            <label class="col-md-3 col-sm-2 control-label">分销佣金状态：</label>
            <div class="col-md-8 col-sm-10">
              <select class="form-control"
                      v-model="params.state">
                <option value="">全部</option>
                <option v-for="(val, key) in commissionStateList"
                        :value="key">{{val}}</option>
              </select>
            </div>
          </div>
        </div>

        <div class="form-horizontal">
          <div class="form-group">
            <label for=""
                   class="col-md-3 col-sm-2 control-label"></label>
            <div class="col-md-8 col-sm-10">
              <button class="btn btn-theme"
                      @click="getCommissionRules(0)"
                      style="color: white;">查询</button>
              <button class="btn btn-theme"
                      @click="showAddRule"
                      style="color: white;"
                      v-res="{code:'menu_0006_0003_0001'}">设置佣金</button>
              <button class="btn btn-theme"
                      v-if="exportBtnShow"
                      @click="exportComissionRules"
                      style="color: white;"
                      v-res="{code:'menu_0006_0003_0003'}">导出</button>
              <button class="btn btn-theme"
                      v-if="!exportBtnShow"
                      @click="exportRepeatMsg"
                      style="color: white; background-color: #999;"
                      v-res="{code:'menu_0006_0003_0003'}">导出{{ timeOut }}</button>
            </div>
          </div>
        </div>

      </div>
      <div class="col-md-12 col-lg-12">

      </div>
    </div>
    <div class="table-responsive report-table">
      <table class="table table-striped table-bordered min-width-1060">
        <thead>
          <tr>
            <th width="10%">序号</th>
            <th width="20%">楼盘名称</th>
            <th width="10%">分销佣金方式</th>
            <th width="10%">合作机构</th>
            <th width="10%">佣金规则</th>
            <th width="8%">生效时间</th>
            <th width="8%">创建时间</th>
            <th width="10%">分销佣金状态</th>
            <th width="25%">操作</th>
          </tr>
        </thead>
        <tbody id="list_body">
          <tr v-for="(row,index) in commissionList">
            <td>{{(params.pageNo-1)*params.pageSize+index+1}}</td>
            <td>{{row.name}}</td>
            <td>{{row.commissionModeStr}}</td>
            <td>{{row.companyName}}</td>
            <td v-if="row.commissionRuleStr.length>=8"><a v-bind:title="row.commissionRuleStr">{{row.commissionRuleStr.substring(0,8)+'...'}}</a></td>
            <td v-if="row.commissionRuleStr.length<8">{{row.commissionRuleStr}}</td>
            <td>{{formatDate(row.effectTime)}}</td>
            <td v-if="row.createTime != null&&row.updateTime!=null&&row.updateTime>row.createTime">{{formatDate(row.updateTime)}}</td>
            <td v-else="row.createTime != null">{{formatDate(row.createTime)}}</td>
            <td>{{row.stateStr}}</td>
            <td style="vertical-align: middle;">
              <button class="btn btn-theme"
                      @click="showRule(row.groupId)"
                      v-res="{code:'menu_0006_0003_0004'}">查看</button>
              <button class="btn btn-theme"
                      v-if="row.state==1"
                      @click="showEditRule(row.ruleParentId,row.groupId)"
                      v-res="{code:'menu_0006_0003_0002'}">编辑</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <div id="laypage_commission_rule"></div>
    <SetRuleModal v-bind:premisesList="premisesList"></SetRuleModal>
    <EditRuleModal v-bind:toEditIds="toEditIds"></EditRuleModal>
  </div>
</template>
<style>
@import url("../../assets/css/multiple-select.css");
#agentCompanys li {
  margin: 5px 30px;
}
.multiple-title {
  border-bottom: 1px solid #ccc;
}
</style>
<script>
import Modal from "../common/modal.vue";
import SetRuleModal from "./setRule.vue";
import EditRuleModal from "./editRule.vue";
export default {
  data() {
    return {
      params: {
        pageNo: 1,
        pageSize: 10,
        premisesId: "",
        createTime: "",
      },
      premisesList: [],
      commissionModeList: [],
      commissionStateList: [],
      createTime: "",
      commissionList: [],
      toEditIds: {
        relationId: "",
        groupId: "",
      },
      companyList: [],
      exportBtnShow: true,
      timeOut: 10,
    };
  },
  components: {
    Modal,
    SetRuleModal,
    EditRuleModal,
  },
  watch: {
    toEditIds: function (val, oldVal) {
      this.initData();
    },
  },
  mounted: function () {
    this.getCompanyList();
    this.getPremiseList();
    this.getCommissionRules();
    this.getCommissionStatusList();
    this.getCommissionWayList();
    this.params.commissionMode = "";
    this.params.state = "";
    this.params.agentOrgId = "";
  },
  methods: {
    //楼盘
    getPremiseList: function () {
      var _self = this;
      var url = _self.utilHelper.apiUrl + "/api/getPremisesForRule";
      var body = {};
      body.params = {};
      _self.$http.post(url, body).then((response) => {
        if (response.body.result == "1") {
          this.premisesList = response.body.resData.list;
        }
      });
    },
    //获取规则列表
    getCommissionRules: function (select) {
      var _self = this;
      if (select == 0) {
        _self.params.pageNo = 1;
      }

      var url = _self.utilHelper.apiUrl + "/api/getCommissionSetPage";
      var body = {};
      body.params = _self.params;
      body.params.premisesId = _self.params.premisesId;
      body.params.commissionMode = _self.params.commissionMode;
      body.params.state = _self.params.state;

      _self.$http.post(url, body).then((response) => {
        var body = response.body;
        if (response.body.result == "1") {
          this.commissionList = body.resData.page.rows;
          var current = body.resData.page.pageNumber;
          var total = body.resData.page.total;
          var totalPages = body.resData.page.totalPages;
          if (totalPages >= 0) {
            layui.laypage.render({
              elem: $("#laypage_commission_rule"), //容器。值支持id名、原生dom对象，jquery对象,
              limit: _self.params.pageSize,
              curr: current,
              count: total,
              theme: "#f87242;", //皮肤
              first: "首页", //若不显示，设置false即可
              last: "尾页", //若不显示，设置false即可
              prev: "上一页", //若不显示，设置false即可
              next: "下一页", //若不显示，设置false即可
              layout: ["prev", "page", "next", "skip", "count"],

              jump: function (obj, first) {
                if (!first) {
                  _self.params.pageNo = obj.curr;
                  _self.getCommissionRules();
                }
              },
            });
          }
        }
      });
    },
    showAddRule: function () {
      $("#addRuleModal").modal("show");
    },
    showEditRule: function (relationId, groupId) {
      this.toEditIds.relationId = relationId;
      this.toEditIds.groupId = groupId;
      $("#editRuleModal").modal("show");
    },
    getCommissionStatusList: function () {
      var _self = this;
      var url = _self.utilHelper.apiUrl + "/common/getEnum/CommisionStateEnum";
      _self.$http.get(url).then((response) => {
        this.commissionStateList = response.body.data;
      });
    },
    //佣金方式
    getCommissionWayList: function () {
      var _self = this;
      var url = _self.utilHelper.apiUrl + "/common/getEnum/CommisionModeEnum";
      _self.$http.get(url).then((response) => {
        this.commissionModeList = response.body.data;
      });
    },
    addZero: function (m) {
      //时间不足10,前面补零
      return m < 10 ? "0" + m : m;
    },
    formatDate: function (time) {
      var createTime = new Date(time);
      var y = createTime.getFullYear();
      var m = createTime.getMonth() + 1;
      var d = createTime.getDate();
      var h = createTime.getHours();
      var mm = createTime.getMinutes();
      var s = createTime.getSeconds();
      //createTime = y+'-'+this.addZero(m)+'-'+this.addZero(d)+' '+this.addZero(h)+':'+this.addZero(mm);
      createTime = y + "-" + this.addZero(m) + "-" + this.addZero(d);
      return createTime;
    },
    showRule: function (id) {
      this.$router.push({
        name: "ruleDetail",
        params: { id: id },
      });
      //                const {href} = this.$router.resolve({
      //                    name: 'ruleDetail',
      //                    params: {id: id}
      //                })
      //				window.open(href,'_blank');
    },
    exportComissionRules() {
      var _self = this;
      if (_self.commissionList.length == 0) {
        layer.msg("当前数据为空，无法导出");
        return;
      }
      _self.exportBtnShow = false;
      const userId = window.localStorage.getItem("1_userId");
      var url =
        _self.utilHelper.apiUrl +
        "/api/commissionRuleExport?params.userId=" +
        userId +
        "&params.id=" +
        _self.params.premisesId +
        "&params.agentOrgId=" +
        _self.params.agentOrgId +
        "&params.loginType=1&params.commissionMode=" +
        _self.params.commissionMode +
        "&params.state=" +
        _self.params.state +
        "&params.creatTime=" +
        _self.params.createTime;
      window.location.href = url;

      var exportInterval = setInterval(function () {
        if (_self.timeOut <= 0) {
          window.clearInterval(exportInterval);
          _self.timeOut = 10;
          _self.exportBtnShow = true;
        } else {
          _self.timeOut -= 1;
        }
      }, 1000);
    },
    exportRepeatMsg: function () {
      var _self = this;
      layer.msg(_self.timeOut + "秒后可再次导出,请稍等片刻!");
      return;
    },
    //获取合作机构
    getCompanyList: function () {
      var _self = this;
      var body = {};
      body.params = {};
      var url = _self.utilHelper.apiUrl + "/api/getAgentOrgByDevOrg";
      _self.$http.post(url, body).then((response) => {
        if (response.body.result == "1") {
          this.companyList = response.body.resData.agentOrgList;
        } else {
          layer.msg("查询条件初始化失败");
        }
      });
    },
  },
};
</script>